package com.ThreadStudy.syn;

public class SafeBuyTicket1 {

    public static void main(String[] args) {
        BuyTicket2 buyTicket = new BuyTicket2();

        Thread thread = new Thread(buyTicket,"小脏");
        Thread thread1 = new Thread(buyTicket,"小王");
        Thread thread2 = new Thread(buyTicket,"小菜");


        thread.start();
        thread1.start();
        thread2.start();


    }
}


class BuyTicket2 implements Runnable{
    private int ticketnum = 10;
    boolean flag = true; // 外部停止方式

    @Override
    public void run() {

        // 买票
        while(flag){
            try {
                buy();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }



    // 加synchronized 同步方法,锁的是this
    private synchronized void buy() throws InterruptedException {
        // 判断是否有票
        if(ticketnum<=0){
            flag = false;
            return;
        }

        // 模拟延时
        Thread.sleep(100);

        // 买票
        System.out.println(Thread.currentThread().getName()+"买到第"+(ticketnum--)+"张票");
    }

}
